package com.duowan.cms.action;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.duowan.cms.common.domain.Page;
import com.duowan.cms.common.exception.BaseCheckedException;
import com.duowan.cms.common.util.DateUtil;
import com.duowan.cms.common.util.LogUtil;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.dto.channel.ChannelInfo;
import com.duowan.cms.dto.template.SimpleTemplateInfo;
import com.duowan.cms.dto.template.TemplateCategory;
import com.duowan.cms.dto.template.TemplateInfo;
import com.duowan.cms.dto.template.TemplateSearchCriteria;
import com.duowan.cms.dto.user.UserInfo;
import com.duowan.cms.dto.user.UserPowerInfo;
import com.duowan.cms.service.channel.ChannelService;
import com.duowan.cms.service.template.TemplateService;
import com.duowan.cms.util.RequestUtil;

@Controller
public class TemplateController extends AbstractController {
	
    @Autowired
    private TemplateService templateService;
    @Autowired
    private ChannelService channelService;

    private static Logger logger = Logger.getLogger(TemplateController.class);
    
    @RequestMapping(value = "/template/templateList", method = RequestMethod.GET)
    public String templateList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String pageNo = request.getParameter("pageNo");
        String channelId = request.getParameter("channelId");
        String type = request.getParameter("type");
        String searchkey = request.getParameter("searchkey");
        String templateCategory = request.getParameter("templateCategory");
        TemplateSearchCriteria searchCriteria = new TemplateSearchCriteria();
        if (!StringUtil.isEmpty(pageNo)) {
            searchCriteria.setPageNo(Integer.parseInt(pageNo));
        }
        if (!StringUtil.isEmpty(templateCategory)) {
            searchCriteria.setTemplateCategory(TemplateCategory.getInstance(templateCategory));
        }
        if ("templateId".equals(type)) {
            searchCriteria.setTemplateId(searchkey);
        } else if ("lastUpdateUserId".equals(type)) {
            searchCriteria.setLastUpdateUserId(searchkey);
        } else if ("createUserId".equals(type)) {
            searchCriteria.setCreateUserId(searchkey);
        } else if ("alias".equals(type)) {
            searchCriteria.setAlias(searchkey);
        } else if ("name".equals(type)) {
            searchCriteria.setName(searchkey);
        }
        
        searchCriteria.setChannelId(channelId);
        Page<SimpleTemplateInfo> templateInfoPage = templateService.pageSearch4Show(searchCriteria);
        String preViewUrl = String.valueOf(request.getSession().getAttribute("preViewUrl")) ;
        request.getSession().removeAttribute("preViewUrl");
        request.setAttribute("templateInfoPage", templateInfoPage);
        request.setAttribute("preViewUrl", StringUtil.isEmpty(preViewUrl) ? "" : preViewUrl);
        request.setAttribute("searchkey", "null".equals(searchkey) ? "" : searchkey);
        request.setAttribute("type", "null".equals(type) ? "" : type);
        request.setAttribute("templateCategory", "null".equals(templateCategory) ? "" : templateCategory);
        request.setAttribute("queryStr", "&searchkey=" + searchkey + "&type=" + type + "&templateCategory=" + templateCategory);
        return "/template/template_list";
    }

    /**
     * 1.只支持复制同一频道的1个模版
     * 2.不支持同时复制不同频道的模版
     */
    @RequestMapping(value = "/template/copyTemplate", method = RequestMethod.GET)
    public void copyTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String channelId = request.getParameter("channelId");
        String templateId = request.getParameter("templateId");
        String templateName = request.getParameter("templateName");
        UserInfo userInfo = (UserInfo)request.getSession().getAttribute("userInfo");
        boolean hasPower =templateService.hasPermissionCopyFinalTemplate(channelId, userInfo , Long.parseLong(templateId) );
        if (!hasPower) {
            response.getWriter().write("[error]:你没有复制/粘贴最终文章页的权限");
            return;
        }

        // 保持["频道name"和"模板name"]这个格式是为了粘贴错误时显示粘贴哪个"频道name"下的哪个"模板name"出错
        ChannelInfo channelInfo = channelService.getById(channelId);
        String tcut = channelId + "," + channelInfo.getName() + ";"+templateId + "," + templateName + ";";
        request.getSession().setAttribute("templatecopy", tcut);
    }

    /**
     * 全复制：复制某个频道到session，方便粘贴的时候取出
     */
    @RequestMapping(value = "/template/copyAllTemplate", method = RequestMethod.GET)
    public void copyAllTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String channelId = request.getParameter("channelId");
        request.getSession().setAttribute("templatecopyall", channelId);
    }

    /**
     * 全粘贴:
     * 校验:
     * 		1.如果没有在其他频道点击”全复制”，就直接点击”全粘贴”.会提示” [error]粘贴全频道模板失败：请到其他频道点击全复制，再到本频道点击全粘贴”
     * 		2.如果直接”全粘贴”到同一频道，会提示“[error]不能把模板粘贴同频道”
     */
    @RequestMapping(value = "/template/pasteAllTemplate", method = RequestMethod.GET)
    public void pasteAllTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException, BaseCheckedException {
        String srcChannelId = String.valueOf(request.getSession().getAttribute("templatecopyall"));
        String channelId = request.getParameter("channelId");
        if (StringUtil.isEmpty(srcChannelId)) {
            response.getWriter().write("[error]粘贴全频道模板失败：请到其他频道点击全复制，再到本频道点击全粘贴");
            throw new BaseCheckedException("", "[error]粘贴全频道模板失败：请到其他频道点击全复制，再到本频道点击全粘贴");
        }
        if (channelId.equals(srcChannelId)) {
            response.getWriter().write("[error]不能把模板粘贴同频道");
            throw new BaseCheckedException("", "[error]不能把模板粘贴同频道");
        }

        TemplateInfo templateInfo = this.configBasicTemplateInfo(request, channelService.getById(srcChannelId).getName());
        String resultStr = templateService.pasteAll(srcChannelId, templateInfo);
        request.getSession().removeAttribute("templatecopyall");
        response.getWriter().write(resultStr);
    }

    /**
     * 配置TemplateInfo的基本信息
     * 粘贴后的模板信息与原模板的信息有以下不同:
     *		1.userIp和proxyIp:为点击”全粘贴”用户所操作所发送请求的ip
     *		2.channelId：为粘贴到的频道id.
     *		3.createUserId(模板创建人)和lastUpdateUserId(模板最后更新人)：为点击”全粘贴”用户
     *		4.log(日志)：为说明粘贴动作的日志，而不是旧日志。
     */
    private TemplateInfo configBasicTemplateInfo(HttpServletRequest request, String srcChannelName) {

        String createUserId = ((UserInfo) request.getSession().getAttribute("userInfo")).getUserId();
        String channelId = request.getParameter("channelId");
        TemplateInfo templateInfo = new TemplateInfo();
        templateInfo.setUserIp(RequestUtil.getUserIp(request));
        templateInfo.setProxyIp(RequestUtil.getProxyIp(request));
        templateInfo.setChannelInfo(channelService.getById(channelId));
        templateInfo.setCreateUserId(createUserId);
        templateInfo.setLastUpdateUserId(createUserId);
        templateInfo.setLogs("用户[" + createUserId + "]在{" + DateUtil.format(new Date(), DateUtil.exportXlsDateCreateTimeFormat) + "}从[" + srcChannelName + "]频道复制模板到本频道");
        return templateInfo;
    }

    @RequestMapping(value = "/template/pasteTemplate", method = RequestMethod.GET)
    public void pasteTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException, BaseCheckedException {
        String channelId = request.getParameter("channelId");
        String templatecopy = (String) request.getSession().getAttribute("templatecopy");
        if (StringUtil.isEmpty(templatecopy)) {
            response.getWriter().write("[error]:没有东西可以粘贴");
            return;
        }
        String oldChannelId = templatecopy.substring(0, templatecopy.indexOf(","));// 旧频道id
        if (channelId.equals(oldChannelId)) {
            response.getWriter().write("[error]:不能把模板粘贴到同一个频道，请粘贴到其他频道");
            return;
        }
        String[] tcuts = templatecopy.split(";");
        long templateId = Long.parseLong(tcuts[1].substring(0, tcuts[1].indexOf(",")));
        TemplateInfo exsitTemplateInfo = templateService.getByChannelIdAndTemplateId(channelId, templateId);
        if(exsitTemplateInfo != null){
        	response.getWriter().write("[error]:本频道已经存在[模版名="+exsitTemplateInfo.getName()+"]的模版");
        	return;
        }
        
        TemplateInfo templateInfo = this.configBasicTemplateInfo(request, channelService.getById(oldChannelId).getName());
        templateService.paste(channelId, templatecopy, templateInfo);
        request.getSession().removeAttribute("templatecopy");// 清空复制粘贴的内容
        response.getWriter().write("/template/templateList.do?channelId=" + channelId);
    }

    @RequestMapping(value = "/template/deleteTemplate", method = RequestMethod.GET)
    public void deleteTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException, BaseCheckedException {
        String channelId = request.getParameter("channelId");
        String templateId = request.getParameter("templateId");
        if (templateService.hasArticleUse(channelId, Long.parseLong(templateId))) {
            response.getWriter().write("[error]:您还有文章在使用该模板，不允许删除！");
            return;
        }

        templateService.delete(channelId, Long.parseLong(templateId));
        response.getWriter().write("/template/templateList.do?channelId=" + channelId);
    }

    @RequestMapping(value = "/template/checkName", method = RequestMethod.GET)
    public void checkName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String channelId = request.getParameter("channelId");
        String name = request.getParameter("name");
        TemplateInfo templateInfo = templateService.getByChannelIdAndTemplateName(channelId, name);
        if (templateInfo == null) {
            response.getWriter().write("noExist");
        } else {
            response.getWriter().write("exist");
        }
    }

    @RequestMapping(value = "/template/toGrammarPage", method = RequestMethod.GET)
    public String toGrammarPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        return "/template/template_grammar";
    }

	@RequestMapping(value = "/template/toAddTemplatePage", method = RequestMethod.GET)
	public String toAddTemplatePage(HttpServletRequest request,HttpServletResponse response) throws IOException {
		 request.setAttribute("isAddTemplate", true);
		 //设置身份 TODO 优化，将信息在过滤器中设置
		 UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo");
		 ChannelInfo channelInfo = (ChannelInfo) request.getSession().getAttribute("channelInfo");
		 for(UserPowerInfo upi : userInfo.getAllChannelPowerInfo()){
            if(channelInfo.getId().equals(upi.getChannelId())){
                request.setAttribute("powerValue", upi.getUserRole().getPowerValue());
                break;
            }
		 }
		 return "/template/template_edit";
	}
	
	
	@RequestMapping(value = "/template/toEditTemplatePage", method = RequestMethod.GET)
	public String toEditTemplatePage(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String channelId = request.getParameter("channelId");
		String templateId = request.getParameter("templateId");
		 TemplateInfo templateInfo = templateService.getByChannelIdAndTemplateId(channelId, Long.parseLong(templateId));
		 String logs = templateInfo.getLogs()	;
		 if (!("".equals(logs) || logs == null)) {
				request.setAttribute("logArr", logs.split("<br>\n") );
		 }
		 request.setAttribute("isAddTemplate", false);
		 request.setAttribute("templateInfo", templateInfo);
		 request.setAttribute("content", StringUtil.escapeHTMLTags(templateInfo.getContent()));
		 request.setAttribute("content2", StringUtil.escapeHTMLTags(templateInfo.getContent2()));
		 request.setAttribute("content3", StringUtil.escapeHTMLTags(templateInfo.getContent3()));
		
		return "/template/template_edit";
	}

    @RequestMapping(value = "/template/publishTemplate", method = RequestMethod.POST)
    public String publishTemplate(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("templateInfo") TemplateInfo templateInfo) throws IOException,
            BaseCheckedException {
        String channelId = request.getParameter("channelId");
        String templateId = request.getParameter("templateId");
        String submitType = request.getParameter("submitType");
        String templateCategorySelector = request.getParameter("templateCategorySelector");
        templateInfo.setChannelInfo(channelService.getById(channelId));
        templateInfo.setTemplateCategory(TemplateCategory.getInstance(templateCategorySelector));
        templateInfo.setProxyIp(RequestUtil.getProxyIp(request));
        templateInfo.setUserIp(RequestUtil.getUserIp(request));
        templateInfo.setLogs(LogUtil.getLogBeforeTen(RequestUtil.getRequestLog(request) + templateInfo.getLogs()));
        if ("submitAndPreview".equals(submitType)) {
        	logger.info("["+channelId+"]频道下的模板["+templateInfo.getName() + "("+templateId+")]提交并预览");
        	String preViewUrl = templateService.publishAndPreview(templateInfo);
        	request.getSession().setAttribute("preViewUrl", preViewUrl);
		}else{
			logger.info("["+channelId+"]频道下的模板["+templateInfo.getName() + "("+templateId+")]提交");
			templateService.publish(templateInfo);
		}
        
        return "redirect:/template/templateList.do?channelId=" + channelId;
    }
    /**
     * 发布最终文章模板:独立出一个方法，是由于权限控制需要，编辑无修改，增加，删除最终文章模板的权限
     */
    @RequestMapping(value = "/template/publishFinalPageTemplate", method = RequestMethod.POST)
    public String publishFinalPageTemplate(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("templateInfo") TemplateInfo templateInfo) throws IOException,
            BaseCheckedException {
    	return this.publishTemplate(request, response, templateInfo);
    }

    /**
     *  检查分类是否已经存在
     */
    @RequestMapping(value = "/template/checkTemplateCategory", method = RequestMethod.GET)
    public void checkTemplateCategoryExist(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String channelId = request.getParameter("channelId");
        String templateCategory = request.getParameter("templateCategory");
        if (!"标签".equals(templateCategory) && !"标签图".equals(templateCategory)) {
            return;
        }
        if (!templateService.isTemplateCategoryExist(channelId, templateCategory)) {
            response.getWriter().write("error:分类为标签或标签图，一个频道只有一个");
        }
    }
    @RequestMapping(value = "/template/checkAlias", method = RequestMethod.GET)
    public void checkAlias(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String channelId = request.getParameter("channelId");
        String alias = request.getParameter("alias");
        String templateIdStr = request.getParameter("templateId");
        Long templateId = null;
        if(!StringUtil.isEmpty(templateIdStr)){
        	templateId = Long.parseLong(templateIdStr);
        }
        if (!templateService.isValidAlias(channelId ,templateId,  alias)) {
        	  response.getWriter().write("error:请输入合法的别名");
		}
    }
    
}
